package com.huzihan;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageMappingInfo;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class MyController {

    @Autowired
    SimpMessagingTemplate template;


    /**
     * 登录
     * @param username
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/login")
    public void login(String username, HttpServletRequest request, HttpServletResponse response)throws IOException {
        Contains.userList.add(username);
        request.getSession().setAttribute("userName",username);
        response.sendRedirect("main.html");
    }


    /**
     * 获取所有的User
     * @return
     */
    @RequestMapping("/userList")
    @ResponseBody
    public String userList(){
        String allUser = "";
        for(String s : Contains.userList){
            allUser += s + ",";
        }

        allUser = allUser.substring(0,allUser.length() - 1);
        template.convertAndSend("/topic/userList",allUser);
        return "success";
    }

    @RequestMapping("/userInfo")
    @ResponseBody
    public String userInfo(HttpServletRequest request,HttpServletResponse response){
        String userName = request.getSession().getAttribute("userName").toString();
        //return "{\"info \": " + "\"" + userName + "\"}";
        return "{\"info\":\""+userName+"\"}";
    }

    @RequestMapping("/chat")
    @ResponseBody
    public String chat(String message,String username){

        System.out.println("消息人:" + username + " : " + message);

        //发送给某一个人
        //convertAndSend("/user/'user3'/aaaa")
        template.convertAndSendToUser(username,"/aaaa",message);
        return "success";
    }
}
